//
//  Network.m
//  AFNetworking
//
//  Created by admin on 2020/5/13.
//

#import "Network.h"
static Network *network = nil;

@implementation Network

+(Network *)share{
    
  
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        network = [Network new];
        network.manager = [AFHTTPSessionManager manager];
        //设置默认请求头
        network.manager.requestSerializer = [AFJSONRequestSerializer serializer];
        [network.manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        network.manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil];
    });
    return network;
}

-(void)sendPost:(NSString *)url param:(NSDictionary *)param  head:(NSDictionary *)head  block:(NetworkEndBlock)block
{
    [_manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [self hederFieldaddTocken];
    NSString *allHeaders = [_manager.requestSerializer modelToJSONString];
    [_manager POST:url parameters:param headers:head progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
     
        NSDictionary *result = nil;
        @try {
            result = responseObject;
        } @catch (NSException *exception) {
            NSError *error = [NSError errorWithDomain:@"" code:1001 userInfo:exception.userInfo];
            NSLog(@"❗️url:%@ \nheader:%@ \nparame:%@ \nerror:%@", url, allHeaders, param, error);
            block(nil, error);
        } @finally {
            
            
            if ([result intValueForKey:@"code" default:0] == 200) {//返回正常
                
                NSDictionary *temresult = result[@"data"];
                NSLog(@"✌️url:%@ \nheader:%@ \nparame:%@ \nresult:%@", url, allHeaders, param, result);
                block(temresult,  nil);
                
            }else{
                NSError *error = [NSError errorWithDomain:result[@"message"] code:1002 userInfo:@{@"errorMsg":result[@"message"]}];
                NSLog(@"❗️url:%@ \nheader:%@ \nparame:%@ \nerror:%@", url, allHeaders, param, error);
                block(nil, error);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"❗️url:%@ \nheader:%@ \nparame:%@ \nerror:%@", url, allHeaders, param, error);
        
        block(nil, [NSError errorWithDomain:@"加载失败" code:error.code userInfo:nil]);
    }];
    
}

/**
 发送GET请求
 
 @param url url
 @param param  请求参数
 @param block 返回信号
 */
-(void)sendGet:(NSString *)url param:(NSDictionary *)param head:(NSDictionary *)head block:(void(^)(NSDictionary *result, NSError *error))block{
     [_manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [self hederFieldaddTocken];
    NSString *allHeaders = [_manager.requestSerializer modelToJSONString];
    [_manager GET:url parameters:param headers:head progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    
        NSDictionary *result = nil;
        @try {
            result = responseObject;
        } @catch (NSException *exception) {
            NSError *error = [NSError errorWithDomain:@"" code:1001 userInfo:exception.userInfo];
            NSLog(@"❗️url:%@ \nheader:%@ \nparame:%@ \nerror:%@", url, allHeaders, param, error);
            block(nil, error);
        } @finally {
            
            
            if ([result floatValueForKey:@"code" default:0] == 200) {//返回正常
                
                NSDictionary *temresult = result[@"data"];
                NSLog(@"✌️url:%@ \nheader:%@ \nparame:%@ \nresult:%@", url, allHeaders, param, result);
                block(temresult,  nil);
                
            }else{
                NSError *error = [NSError errorWithDomain:result[@"message"] code:1002 userInfo:@{@"errorMsg":result[@"message"]}];
                NSLog(@"❗️url:%@ \nheader:%@ \nparame:%@ \nerror:%@", url, allHeaders, param, error);
                block(nil, error);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"❗️url:%@ \nheader:%@ \nparame:%@ \nerror:%@", url, allHeaders, param, error);
        
        block(nil, [NSError errorWithDomain:@"加载失败" code:error.code userInfo:nil]);
    }];
}

-(void)sendPut:(NSString *)url param:(NSDictionary *)param head:(NSDictionary *)head block:(NetworkEndBlock)block{
     [_manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [self hederFieldaddTocken];
    NSString *allHeaders = [_manager.requestSerializer modelToJSONString];
    
    [_manager PUT:url parameters:param headers:head success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
 
        NSDictionary *result = nil;
        @try {
            result = responseObject;
        } @catch (NSException *exception) {
            NSError *error = [NSError errorWithDomain:@"" code:1001 userInfo:exception.userInfo];
            NSLog(@"❗️url:%@ \nheader:%@ \nparame:%@ \nerror:%@", url, allHeaders, param, error);
            block(nil, error);
        } @finally {
            
            
            if ([result floatValueForKey:@"code" default:0] == 200) {//返回正常
                
                NSDictionary *temresult = result[@"data"];
                NSLog(@"✌️url:%@ \nheader:%@ \nparame:%@ \nresult:%@", url, allHeaders, param, result);
                block(temresult,  nil);
                
            }else{
                NSError *error = [NSError errorWithDomain:result[@"message"] code:1002 userInfo:@{@"errorMsg":result[@"message"]}];
                NSLog(@"❗️url:%@ \nheader:%@ \nparame:%@ \nerror:%@", url, allHeaders, param, error);
                block(nil, error);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"❗️url:%@ \nheader:%@ \nparame:%@ \nerror:%@", url, allHeaders, param, error);
        
        block(nil, [NSError errorWithDomain:@"加载失败" code:error.code userInfo:nil]);
    }];
}

-(void)sendDelete:(NSString *)url param:(NSDictionary *)param head:(NSDictionary *)head block:(NetworkEndBlock)block{
     [_manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [self hederFieldaddTocken];
    NSString *allHeaders = [_manager.requestSerializer modelToJSONString];
    
    [_manager DELETE:url parameters:param headers:head success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    
        NSDictionary *result = nil;
        @try {
            result = responseObject;
        } @catch (NSException *exception) {
            NSError *error = [NSError errorWithDomain:@"" code:1001 userInfo:exception.userInfo];
            NSLog(@"❗️url:%@ \nheader:%@ \nparame:%@ \nerror:%@", url, allHeaders, param, error);
            block(nil, error);
        } @finally {
            
            
            if ([result floatValueForKey:@"code" default:0] == 200) {//返回正常
                
                NSDictionary *temresult = result[@"data"];
                NSLog(@"✌️url:%@ \nheader:%@ \nparame:%@ \nresult:%@", url, allHeaders, param, result);
                block(temresult,  nil);
                
            }else{
                NSError *error = [NSError errorWithDomain:result[@"message"] code:1002 userInfo:@{@"errorMsg":result[@"message"]}];
                NSLog(@"❗️url:%@ \nheader:%@ \nparame:%@ \nerror:%@", url, allHeaders, param, error);
                block(nil, error);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"❗️url:%@ \nheader:%@ \nparame:%@ \nerror:%@", url, allHeaders, param, error);
        
        block(nil, [NSError errorWithDomain:@"加载失败" code:error.code userInfo:nil]);
    }];
}
//
//-(void)sendPostImage:(NSString *)url image:(UIImage *)image progress:(void(^)(NSProgress *_Nonnull uploadProgress))progress block:(void(^)(NSDictionary *result, NSError *error))block{
//
//    [self hederFieldaddTocken];
//    [_manager.requestSerializer setTimeoutInterval:30.0];
//    [_manager.requestSerializer setValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];
//    NSString *allHeaders = [_manager.requestSerializer modelToJSONString];
//
//    [_manager POST:url parameters:@{} constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
//        NSData *imageData =UIImageJPEGRepresentation(image,1);
//        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//        formatter.dateFormat =@"yyyyMMddHHmmss";
//        NSString *str = [formatter stringFromDate:[NSDate date]];
//        NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str];
//        [formData appendPartWithFileData:imageData name:@"file" fileName:fileName
//                                mimeType:@"image/jpeg"];
//
//
//    } progress:progress
//                      success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSDictionary *result = nil;
//        @try {
//            result = [self returnDictionaryWithDataPath:responseObject];
//        } @catch (NSException *exception) {
//            NSError *error = [NSError errorWithDomain:@"" code:1001 userInfo:exception.userInfo];
//            DDLogWarn(@"❗️url:%@ \nheader:%@  \nerror:%@", url, allHeaders, error);
//            block(nil, error);
//        } @finally {
//
//
//            if ([result floatValueForKey:@"code" default:0] == 200) {//返回正常
//
//                NSDictionary *temresult = result[@"data"];
//                DDLogWarn(@"✌️url:%@ \nheader:%@ \nresult:%@", url, allHeaders, result);
//                block(temresult,  nil);
//
//            }else{
//                NSError *error = [NSError errorWithDomain:result[@"message"] code:1002 userInfo:@{@"errorMsg":result[@"message"]}];
//                DDLogInfo(@"❗️url:%@ \nheader:%@ \nerror:%@", url, allHeaders, error);
//                block(nil, error);
//            }
//        }
//
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        DDLogWarn(@"❗️url:%@ \nheader:%@ \nerror:%@", url, allHeaders, error);
//
//        block(nil, [NSError errorWithDomain:@"上传失败" code:error.code userInfo:nil]);
//    }];
//}



/**
 头部添加tocken
 */
-(void)hederFieldaddTocken{
    [_manager.requestSerializer setTimeoutInterval:5.0];
    //设置请求头
//    NSString *str = Global.sharedInstance.user.loginToken;
//    [_manager.requestSerializer setValue:str forHTTPHeaderField:@"Account_Authorization"];

//    if (str.length>0) {
//         [_manager.requestSerializer setValue:str forHTTPHeaderField:@"Account_Authorization"];
//    }
    
}

- (void)setHTTPHeaderField:(NSDictionary *)headerfield{
    NSArray *keys = headerfield.allKeys;
    for (int i=0; i<keys.count; i++) {
        NSString *key = keys[i];
        NSString *value = [headerfield objectForKey:key];
        [_manager.requestSerializer setValue:value forHTTPHeaderField:key];
    }
    
}

@end
